package ms.platform.plan.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import ms.platform.plan.dto.FactoryDto;
import ms.platform.plan.dto.ModelDto;
import ms.platform.plan.dto.TargetDto;
import ms.platform.plan.model.ModelMeterPlan;
import ms.platform.plan.service.BusModelService;
import ms.platform.plan.service.ModelPlanMeterService;
import ms.platform.progress.dto.MeterUsedDto;
import ms.platform.progress.service.FactoryPlanService;
import ms.platform.system.controller.BaseController;
import ms.platform.util.PageUtils;
import ms.platform.util.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bus/meter/")
public class MeterController extends BaseController {
    @Autowired
    ModelPlanMeterService modelPlanMeterService;
    @Autowired
    BusModelService busModelService;
    @Autowired
    FactoryPlanService factoryService;
    private Logger logger = LoggerFactory
            .getLogger(MeterController.class);

    /**
     * 计划入库列表
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/meterList")
    public String meterList(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        //总条数
        map.put("count", modelPlanMeterService.queryBusModelAllMeterCount(map));
        List<ModelMeterPlan> list = modelPlanMeterService.queryPageBusModelAllMeterList(PageUtils.Page(request, map));
        List<FactoryDto> factoryDto = busModelService.queryAllFactory("F");
        request.setAttribute("factory", factoryDto);
        request.setAttribute("list", list);
        PageUtils.calculate(map);
        request.getSession().setAttribute("queryMeterList", map);
        return "meter/meterList";
    }

    @RequestMapping(value = "/toAdd")
    public String toEdit(HttpServletRequest request) {

        return "meter/add";
    }

    /**
     * 保存材料信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/addMeter", method = RequestMethod.POST)
    @ResponseBody
    public Object addMeter(@RequestParam Map<String, Object> param, HttpServletRequest request) {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("meterData") == null ? "" : param.get("meterData").toString();
        List<ModelMeterPlan> meter = JSONArray.parseArray(jsonData, ModelMeterPlan.class);
        for (ModelMeterPlan modelMeterPlan : meter) {
            ModelDto modelDto = busModelService.queryBusModelByModelCode(modelMeterPlan.getModelCode());
            modelMeterPlan.setModelCode(modelMeterPlan.getModelCode().trim());
            modelMeterPlan.setAvaliablAmount(modelMeterPlan.getInventory());
            modelMeterPlan.setInsertedBy(adminId);
            modelMeterPlan.setInsertedAt(new Date());
            modelMeterPlan.setUpdatedBy(adminId);
            modelMeterPlan.setUpdatedAt(new Date());

            modelPlanMeterService.saveBusModelMeterPlan(modelMeterPlan);
            //新增下发台账
            //材料入库多少就支给厂家多少，全部支给
            modelMeterPlan.setMeterId(modelMeterPlan.getId());
            modelMeterPlan.setModelId(modelDto.getId());
            modelMeterPlan.setModelPlanId(modelDto.getModelPlanId());
            modelMeterPlan.setGiveAmount(modelMeterPlan.getInventory());
            modelMeterPlan.setAvaliablAmount(modelMeterPlan.getInventory());
            modelMeterPlan.setPlanNum(modelMeterPlan.getInventory());
            modelPlanMeterService.updateInventory(modelMeterPlan);
            busModelService.saveBusModelMeterPlan(modelMeterPlan);
            modelPlanMeterService.saveBusMeterGiveRecord(modelMeterPlan);
        }
        return returnSuccess("操作成功", meter);
    }
    /**
     * 跳转到材料修改页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public String toAdd(HttpServletRequest request,@RequestParam Map<String, String> param) {
    	Integer id = Integer.parseInt(param.get("mapId"));
        request.setAttribute("map", param);
    	ModelMeterPlan meter = modelPlanMeterService.queryMeterInfoById(id);
    	request.setAttribute("meter", meter);
        return "meter/edit";
    }
    
    /**
     * 修改材料信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/editMeter", method = RequestMethod.POST)
    @ResponseBody
    public Object editMeter(@RequestParam Map<String, Object> param, HttpServletRequest request) {
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("meterData") == null ? "" : param.get("meterData").toString();
        List<ModelMeterPlan> meter = JSONArray.parseArray(jsonData, ModelMeterPlan.class);
        for (ModelMeterPlan modelMeterPlan : meter) {
            ModelDto modelDto = busModelService.queryBusModelByModelCode(modelMeterPlan.getModelCode());
            modelMeterPlan.setModelCode(modelMeterPlan.getModelCode().trim());
            modelMeterPlan.setAvaliablAmount(modelMeterPlan.getInventory());
            modelMeterPlan.setUpdatedBy(adminId);
            modelMeterPlan.setUpdatedAt(new Date());
            modelPlanMeterService.editMeterInfoById(modelMeterPlan);
            //新增下发台账
            //材料入库多少就支给厂家多少，全部支给
            modelMeterPlan.setMeterId(modelMeterPlan.getId());
            modelMeterPlan.setModelId(modelDto.getId());
            modelMeterPlan.setModelPlanId(modelDto.getModelPlanId());
            modelMeterPlan.setGiveAmount(modelMeterPlan.getInventory());
            modelMeterPlan.setAvaliablAmount(modelMeterPlan.getInventory());
            modelMeterPlan.setPlanNum(modelMeterPlan.getInventory());
            modelPlanMeterService.updateInventory(modelMeterPlan);
            modelPlanMeterService.editMeterPlanByMeterId(modelMeterPlan);
            modelPlanMeterService.editMeterGiveByMeterId(modelMeterPlan);
        }
        return returnSuccess("操作成功", meter);
    }
    
    /**
     * 材料库存列表
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        try {
            if (!StringUtil.isNullOrBlock(map.get("factory"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("factory")))) {
                    String fac = (String) map.get("factory");
                    map.put("factory",new String(fac.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            if (!StringUtil.isNullOrBlock(map.get("modelCode"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelCode")))) {
                    String mode = (String) map.get("modelCode");
                    map.put("modelCode",new String(mode.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //总条数
        map.put("count", modelPlanMeterService.queryBusModelMeterCount(map));
        List<ModelMeterPlan> list = modelPlanMeterService.queryPageBusModelMeterList(PageUtils.Page(request, map));
        List<FactoryDto> factoryDto = busModelService.queryAllFactory("F");
        request.setAttribute("factory", factoryDto);
        request.setAttribute("list", list);
        PageUtils.calculate(map);
        request.getSession().setAttribute("queryPageBusModelMeter", map);
        return "meter/list";
    }

    /**
     * 统计剩余库存数
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/sumInventory", method = RequestMethod.POST)
    @ResponseBody
    public Object sumInventory(@RequestParam String modelCode, HttpServletRequest request) {
        Integer inventory = modelPlanMeterService.sumInventoryByModelCode(modelCode);
        return returnSuccess("操作成功", inventory);
    }

    /**
     * 跳转到支给页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toLssued")
    public String toLssued(String modelCode, String operator, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String code = modelCode;
        String ope = operator;
        try {
            if (!StringUtil.isNullOrBlock(modelCode)) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(modelCode))) {
                    code = new String(modelCode.getBytes("ISO-8859-1"), "utf-8"); //转码UTF8
                }
            }
            if (!StringUtil.isNullOrBlock(operator)) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(operator))) {
                    ope = new String(operator.getBytes("ISO-8859-1"), "utf-8"); //转码UTF8
                }
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("modelCode", code);
        ModelMeterPlan meter = modelPlanMeterService.getMeterInfoByModelCode(code);
        Integer avaliablAmount = modelPlanMeterService.sumInventoryByModelCode(code);
        List<FactoryDto> factoryDto = busModelService.queryAllFactory("F");
        request.setAttribute("factory", factoryDto);
        if (avaliablAmount != null) {
            meter.setAvaliablAmount(avaliablAmount);
        }
        meter.setFactory(ope);//赋值厂商
        request.setAttribute("meter", meter);
        return "meter/lssued";
    }

    /**
     * 跳转到支给详情页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toLssuedDetails")
    public String toLssuedDetails(String modelCode, HttpServletRequest request) {
        String code = modelCode;
        try {
            if (!StringUtil.isNullOrBlock(modelCode)) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(modelCode))) {
                    code = new String(modelCode.getBytes("ISO-8859-1"), "utf-8"); //转码UTF8}
                }
            }
            ModelDto modelDto = busModelService.queryBusModelByModelCode(code);
            if (modelDto != null) {
                List<ModelMeterPlan> modelMeterPlans = modelPlanMeterService.getLssuedDetails(modelDto.getModelPlanId());
                request.setAttribute("modelMeterPlans", modelMeterPlans);
                request.setAttribute("modelCode", code);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "meter/lssuedDetails";
    }

    @RequestMapping(value = "/toLssuedDetails/toEdit")
    public @ResponseBody
    Map<String, Object> getLssuedDetailsToEdit(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        ModelMeterPlan modelMeterPlan = modelPlanMeterService.getLssuedDetailsToEdit(id);
        map.put("modelMeterPlan", modelMeterPlan);
        return map;
    }

    @RequestMapping(value = "/toLssuedDetails/save")
    public String getLssuedDetailsSave(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        String modelCode = "";
        try {
            if (map != null) {
                modelCode = (String) map.get("modelCode");
                ModelMeterPlan modelMeterPlan = new ModelMeterPlan();
                modelMeterPlan.setStatus((String) map.get("status"));
                modelMeterPlan.setUseFor((String) map.get("useFor"));

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = sdf.parse((String) map.get("giveTime"));
                modelMeterPlan.setGiveTime(date);
                if (map.get("id") != null) {
                    modelMeterPlan.setId(Integer.valueOf(map.get("id").toString()));
                }
                int planNum = 0;
                if (map.get("giveAmount") != null) {
                    modelMeterPlan.setGiveAmount(Integer.valueOf(map.get("giveAmount").toString()));
                    planNum = Integer.valueOf(map.get("giveAmount").toString());
                }
                modelMeterPlan.setModelCode(modelCode);
                String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
                modelMeterPlan.setUpdatedBy(adminId);
                modelMeterPlan.setUpdatedAt(new Date());
                Integer avaliablAmount = modelPlanMeterService.sumInventoryByModelCode(modelCode);
                if (null != avaliablAmount) {
                    //更新库存 如果是提交则执行 0为保存 1提交
                    if (!"0".equals(modelMeterPlan.getStatus())) {
                        modelMeterPlan.setPlanNum(planNum);
                        modelPlanMeterService.updateInventory(modelMeterPlan);
                    }
                    modelPlanMeterService.updateLssuedDetails(modelMeterPlan);
                    request.setAttribute("msg", "00");
                } else {
                    request.setAttribute("msg", "系统错误");
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "redirect:/bus/meter/toLssuedDetails?modelCode=" + modelCode;
    }

    /**
     * 保存支给信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/saveModelMeter", method = RequestMethod.POST)
    @ResponseBody
    public Object saveModelMeter(@RequestParam Map<String, Object> param, HttpServletRequest request) {
        String msg = "操作成功";
        String adminId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        String jsonData = param.get("meterData") == null ? "" : param.get("meterData").toString();
        List<ModelMeterPlan> meter = JSONArray.parseArray(jsonData, ModelMeterPlan.class);
        for (ModelMeterPlan modelMeterPlan : meter) {
            ModelDto modelDto = busModelService.queryBusModelByModelCode(modelMeterPlan.getModelCode());
            if (null != modelDto) {
                modelMeterPlan.setModelId(modelDto.getId());
                modelMeterPlan.setModelPlanId(modelDto.getModelPlanId());
                modelMeterPlan.setInsertedBy(adminId);
                modelMeterPlan.setInsertedAt(new Date());
                modelMeterPlan.setUpdatedBy(adminId);
                modelMeterPlan.setUpdatedAt(new Date());
                modelMeterPlan.setGiveAmount(modelMeterPlan.getPlanNum());
                modelMeterPlan.setAvaliablAmount(modelMeterPlan.getPlanNum());
                Integer avaliablAmount = modelPlanMeterService.sumInventoryByModelCode(modelMeterPlan.getModelCode());
                if (null != avaliablAmount) {
                    if (modelMeterPlan.getPlanNum() <= avaliablAmount) {
                        //更新库存 如果是提交则执行 0为保存 1提交
                        if ("1".equals(modelMeterPlan.getStatus())) {
                            modelPlanMeterService.updateInventory(modelMeterPlan);
                        }
                        busModelService.saveBusModelMeterPlan(modelMeterPlan);
                        if (null != modelMeterPlan.getId()) {
                            //新增下发台账
                            modelPlanMeterService.saveBusMeterGiveRecord(modelMeterPlan);
                        }
                    } else {
                        msg = "库存不足";
                    }
                } else {
                    msg = "系统错误";
                }
            } else {
                msg = "未找到相关计划";
            }

        }
        return returnSuccess(msg, meter);
    }

    /**
     * 根据id查询材料信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/queryMeterInfoByModelCode", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;"})
    @ResponseBody
    public Object queryMeterInfoByModelCode(@RequestParam String modelCode, HttpServletRequest request) {
        ModelMeterPlan meter = modelPlanMeterService.queryMeterInfoByModelCode(modelCode);
        return JSONObject.toJSONString(meter);
    }

    /**
     * 材料下发列表
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/meterGiveList")
    public String meterGiveList(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        List<ModelMeterPlan> list = modelPlanMeterService.getMeterGiveRecord(map, request, userId);
        List<TargetDto> mTypeList = busModelService.queryAllmodelType();
        request.setAttribute("mTypeList", mTypeList);
        request.setAttribute("list", list);
        request.getSession().setAttribute("meterGiveList", map);
        return "progress/meterUse";
    }

    /**
     * 跳转到v材料使用新增
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toMeterUseAdd")
    public String toMeterAdd(String id, HttpServletRequest request) {
        String userId = (String) request.getSession().getAttribute("admin");//当前操作的人id
        ModelMeterPlan meter = modelPlanMeterService.getMeterInfoById(id, userId);
        request.setAttribute("meter", meter);
        return "progress/meterUseAdd";
    }

    /**
     * 材料下发列表2
     *
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/meterGiveListTwo")
    public String meterGiveListTwo(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        try {
            //判断是否乱码
            //机种
            if (!StringUtil.isNullOrBlock(map.get("modelType"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelType")))) {
                    String fac = (String) map.get("modelType");
                    map.put("modelType",new String(fac.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            //modelLevel难易度
            if (!StringUtil.isNullOrBlock(map.get("modelLevel"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelLevel")))) {
                    String temp = (String) map.get("modelLevel");
                    map.put("modelLevel",new String(temp.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            //部品番号
            if (!StringUtil.isNullOrBlock(map.get("modelCode"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("modelCode")))) {
                    String temp = (String) map.get("modelCode");
                    map.put("modelCode",new String(temp.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            //厂家
            if (!StringUtil.isNullOrBlock(map.get("factory"))) {
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode((String) map.get("factory")))) {
                    String temp = (String) map.get("factory");
                    map.put("factory",new String(temp.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        List<ModelMeterPlan> list = modelPlanMeterService.getMeterGiveRecord(map, request, "");
        List<TargetDto> mTypeList = busModelService.queryAllmodelType();
        List<FactoryDto> factoryDto = busModelService.queryAllFactory("F");
        request.setAttribute("factory", factoryDto);
        request.setAttribute("mTypeList", mTypeList);
        request.setAttribute("list", list);
        request.getSession().setAttribute("meterGiveListTwo", map);
        return "meter/meterUse";
    }

    /**
     * 跳转到v材料使用详细
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/toMeterUseViewTwo")
    public String toMeterUseViewTwo(@RequestParam Map<String, Object> map, HttpServletRequest request) {
        map.put("modelCode", map.get("modelCode"));
        List<MeterUsedDto> list = factoryService.queryMeterUsedDetails(map, request);
        request.setAttribute("list", list);
        request.setAttribute("modelCode", map.get("modelCode"));
        request.setAttribute("useFor", map.get("useFor"));
        return "meter/meterUseView";
    }

    //返回中转
    @RequestMapping(value = "/returnMeterGive")
    public ModelAndView returnMeterGive(@RequestParam String url, String flg, HttpServletRequest request) {
        Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute(flg);
        return new ModelAndView(new RedirectView(url), map);
    }

    /**
     * 导入材料
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/importMeter")
    public Object filesUpload(@RequestParam(value = "file", required = false) MultipartFile file,
                              HttpServletRequest request) throws IOException {
    	Map<String, Object> map = new HashMap<String, Object>();
        ObjectMapper mapper = new ObjectMapper();
        String content = "";
        //当前操作的人id
        String userId = (String) request.getSession().getAttribute("admin");
        String result = "";
        //创建处理EXCEL的类  
        MeterReadExcel readExcel = new MeterReadExcel();
        //解析excel，获取上传的事件单  
        List<Map<String, Object>> mList = readExcel.getExcelInfo(file);
        //将excel中的数据转换到list里面,保存到数据库
        for (Map<String, Object> meter : mList) {
        	ModelDto modelDto = busModelService.queryBusModelByModelCode(meter.get("modelCode").toString().trim());
        	if(null == modelDto){
        		map.put("result", meter.get("modelCode").toString().trim());
                content = mapper.writeValueAsString(map);
        		return content;
        	}
        }
        for (Map<String, Object> meter : mList) {
            ModelMeterPlan mDto = new ModelMeterPlan();
            ModelDto modelDto = busModelService.queryBusModelByModelCode(meter.get("modelCode").toString().trim());

            mDto.setModelCode(meter.get("modelCode").toString().trim());
            mDto.setUseFor(meter.get("useFor").toString());
            mDto.setTall(Float.parseFloat(meter.get("tall").toString()));
            mDto.setGrow(Float.parseFloat(meter.get("grow").toString()));
            mDto.setWide(Float.parseFloat(meter.get("wide").toString()));
            mDto.setPerNum(Integer.parseInt(meter.get("perNum").toString()));
            mDto.setPlanAmount(Integer.parseInt(meter.get("planAmount").toString()));
            mDto.setInventory(Integer.parseInt(meter.get("inventory").toString()));
            mDto.setAvaliablAmount(Integer.parseInt(meter.get("inventory").toString()));
            mDto.setInsertedBy(userId);
            mDto.setInsertedAt(new Date());
            mDto.setUpdatedBy(userId);
            mDto.setUpdatedAt(new Date());

            //新增下发台账
            //材料入库多少就支给厂家多少，全部支给
            mDto.setModelId(modelDto.getId());
            mDto.setModelPlanId(modelDto.getModelPlanId());
            mDto.setGiveAmount(mDto.getInventory());
            mDto.setAvaliablAmount(mDto.getInventory());
            mDto.setPlanNum(mDto.getInventory());
            //保存材料
            modelPlanMeterService.saveBusModelMeterPlan(mDto);
            mDto.setMeterId(mDto.getId());
            modelPlanMeterService.updateInventory(mDto);
            busModelService.saveBusModelMeterPlan(mDto);
            modelPlanMeterService.saveBusMeterGiveRecord(mDto);

        }
        if (mList != null && !mList.isEmpty()) {
            result = "success";
        } else {
            result = "error";
        }
        try {
            map.put("result", result);
            content = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return content;
    }
}
